!pr1
Sly Hex Conversion.........................Bob Sander-Cederlof

Have you ever wondered what would happen if you added, in the 6502 decimal mode,values that were not decimal?  I have.  I also wondered if any of the results might be useful.

For example, what happens if I add 0 to $0A, in decimal mode?  The following little piece of code will tell me:

       CLC
       SED             set decimal mode
       LDA #$0A
       ADC #0
       CLD             clear decimal mode
       JMP $FDDA       monitor print byte routine

Lo!  The $0A turns into $10!  It makes sense, because of course adding zero does not change anything.  But the automatic "decimal adjust" that occurs after the add when the 6502 is in decimal mode detects the "A" nybble, generates a carry to the next nybble, and subtracts $0A.

It turns out the same process turns $0B into $11, $0C into $12, and so on up to $0F into $15.

That is a useful result!  That means that I can convert a hex nybble to BCD byte by merely adding zero when in decimal mode!

A little further experimentation will lead to another useful trick.  If I add first $90 and then $40, both additions in decimal mode, a value between $00 and $0F will be converted to the ASCII code for the digits 0-9 and letter A-F.  Believe it or not!

The first addition, of $90, gives us $90-$9F.  The automatic "decimal adjust" does nothing to $90-$99, and carry will be clear afterwards.  If the intermediate result was $9A-$9F, the decimal adjust will first generate a nybble carry because the A-F nybble is greater than 9, and reduce that nybble by A.  The nybble carry will increment the 9 nybble to A, which gets reduced back to 0 and a byte carry is set.  This means we end up with $90-$99 with carry clear or $00-$05 with carry set.

Adding $40 in the next step brings the $90-$99 up to $30-$39 (with carry out of the byte, which we will ignore).  The $00-$05 will be brought up to $41-$45, ASCII codes for A-F.  Voila!

Useful, but maybe not the best.  It turns out that a more traditional approach is only one byte longer and saves a few cycles.  With the value $00-$0F in the A-register:

       CMP #$0A
       BCC .1          0-9
       ADC #6          convert A-F to $11-16
   .1  ADC #$30

will convert to ASCII.
